local addonName = "SmartHealIndicator"
local frame = CreateFrame("Frame", addonName.."Frame", UIParent)
local holyLightIcon = "Interface\\Icons\\Spell_Holy_HolyBolt"
local flashOfLightIcon = "Interface\\Icons\\Spell_Holy_FlashHeal"
-- 添加本地存储（约第5行后）
local SETTINGS = {
    autoBeacon = false
}

-- 在文件顶部添加（约第5行后）
local BEACON_SPELL_ID = 53563  -- 根据实际道标法术ID修改
local INDICATOR_SIZE = 5  -- 每个状态块尺寸

-- 配置数据 --
local BLESSING_INFO = {
    ["智慧祝福"] = {
        icon = "Interface\\Icons\\Spell_Holy_SealOfWisdom",
        spellIDs = { 19852, 19853, 25894, 25290, 27142 }, -- 普通+强效智慧祝福
        checkFunc = function()
            return GetSpellInfo(19852)  -- 返回基础法术名称
        end
    },
    ["力量祝福"] = {
        icon = "Interface\\Icons\\Spell_Holy_FistOfJustice",
        spellIDs = { 19836, 25782 }, -- 普通+强效力量祝福
        checkFunc = function()
            return GetSpellInfo(19836)
        end
    },
    ["王者祝福"] = {
        icon = "Interface\\Icons\\Spell_Magic_GreaterBlessingofKings",
        spellIDs = { 20217, 25898 }, -- 普通+强效王者祝福
        checkFunc = function()
            return GetSpellInfo(20217)
        end
    }
}


-- 创建独立框架容器
local healFrame = CreateFrame("Frame", nil, UIParent)
healFrame:SetSize(40, 40)
healFrame:SetPoint("CENTER", UIParent, "CENTER", 0, -100)

-- 治疗提示图标（单独框架）
local healIcon = healFrame:CreateTexture(nil, "OVERLAY")
healIcon:SetAllPoints()
healIcon:SetTexture(holyLightIcon)
healIcon:Hide()

-- 原dragFrame仅用于祝福提示
local dragFrame = CreateFrame("Frame", nil, UIParent)
dragFrame:SetSize(105, 35)  -- 3个图标总宽35 * 3=105
dragFrame:SetPoint("CENTER", healFrame, "CENTER", 0, -50)  -- 位于治疗图标下方

-- 设置拖动逻辑 --
dragFrame:SetScript("OnDragStart", function(self)
    self:StartMoving()
end)

dragFrame:SetScript("OnDragStop", function(self)
    self:StopMovingOrSizing()
end)

-- 创建道标状态指示器框架
local beaconFrame = CreateFrame("Frame", addonName.."BeaconFrame", UIParent)
beaconFrame:SetFrameLevel(1)
beaconFrame:SetSize(INDICATOR_SIZE, INDICATOR_SIZE)
beaconFrame:SetPoint("TOPLEFT", UIParent, "TOPLEFT", 0, 0)

-- 创建状态指示纹理
local beaconIndicator = beaconFrame:CreateTexture(nil, "BACKGROUND")
beaconIndicator:SetColorTexture(1, 0, 0, 1)  -- 默认红色
-- 设置纹理对齐方式,完全填充父框架,自动对齐,动态适配
beaconIndicator:SetAllPoints()

-- 创建间隔纹理
local splitTexture = beaconFrame:CreateTexture(nil, "BACKGROUND")
splitTexture:SetColorTexture(0.5, 0.5, 0.5, 1)
splitTexture:SetPoint("LEFT", beaconFrame, "RIGHT", 0, 0)
splitTexture:SetSize(1, INDICATOR_SIZE)

-- 创建开关控制指示器
local switchFrame = CreateFrame("Frame", addonName.."SwitchFrame", UIParent)
switchFrame:SetFrameLevel(1)
switchFrame:SetSize(INDICATOR_SIZE, INDICATOR_SIZE)
switchFrame:SetPoint("LEFT", splitTexture, "RIGHT", 0, 0)

-- 新增第二个分割线（在开关框架右侧）
local splitTexture2 = beaconFrame:CreateTexture(nil, "BACKGROUND")  -- 使用同一个父框架
splitTexture2:SetColorTexture(0.5, 0.5, 0.5, 1)
splitTexture2:SetPoint("LEFT", switchFrame, "RIGHT", 0, 0)  -- 锚点到开关框架右侧
splitTexture2:SetSize(1, INDICATOR_SIZE)  -- 保持相同尺寸

local switchIndicator = switchFrame:CreateTexture(nil, "BACKGROUND")
switchIndicator:SetColorTexture(1, 0, 0, 1)  -- 默认关闭状态（红色）
switchIndicator:SetAllPoints()

local SWITCH_STATE = false  -- 开关状态变量

-- 添加点击交互功能
switchFrame:EnableMouse(true)
switchFrame:SetScript("OnMouseDown", function(self)
    SETTINGS.autoBeacon = not SETTINGS.autoBeacon
    SWITCH_STATE = SETTINGS.autoBeacon
    SWITCH_STATE = not SWITCH_STATE
    switchIndicator:SetColorTexture(SWITCH_STATE and 0 or 1, SWITCH_STATE and 1 or 0, 0, 0.8)
    print("自动道标开关:", SWITCH_STATE and "开启" or "关闭")
end)

-- 添加悬停提示
switchFrame:SetScript("OnEnter", function()
    GameTooltip:SetOwner(switchFrame, "ANCHOR_RIGHT")
    GameTooltip:AddLine("自动道标控制")
    GameTooltip:AddLine("当前状态: "..(SWITCH_STATE and "|cFF00FF00开启" or "|cFFFF0000关闭"))
    GameTooltip:Show()
end)
switchFrame:SetScript("OnLeave", GameTooltip_Hide)

-- 图标池管理 --
local blessingIcons = {}
for i, blessName in ipairs({"王者祝福", "智慧祝福", "力量祝福"}) do
    local icon = dragFrame:CreateTexture(nil, "OVERLAY")
    icon:SetSize(30, 30)
    icon:SetPoint("LEFT", dragFrame, "LEFT", (i-1)*35, 0)
    icon:SetTexture(BLESSING_INFO[blessName].icon)
    icon:Hide()
    blessingIcons[blessName] = icon
end

-- 拖动逻辑 --
dragFrame:SetScript("OnDragStart", dragFrame.StartMoving)
dragFrame:SetScript("OnDragStop", dragFrame.StopMovingOrSizing)

-- 其他代码（事件、函数等）放在图标定义之后 --
frame:RegisterEvent("PLAYER_TARGET_CHANGED")
frame:RegisterEvent("UNIT_AURA")
frame:RegisterEvent("UNIT_HEALTH")
frame:RegisterEvent("UNIT_MAXHEALTH")
frame:RegisterEvent("SPELL_POWER_CHANGED")
frame:RegisterEvent("PLAYER_FOCUS_CHANGED")

-- 添加焦点检测函数（放在GetCritChance函数前）
local function UpdateBeaconIndicator()
    local isValidFocus = UnitExists("focus") and UnitIsPlayer("focus")
    local needsBeacon = true
    if isValidFocus then
        for i=1, 40 do
            local _, _, _, _, _, _, _, _, _, spellId = UnitAura("focus", i, "HELPFUL")
            if spellId == BEACON_SPELL_ID then
                needsBeacon = false
                break
            end
        end
    else
        needsBeacon = true  -- 无焦点时强制显示需要补
    end

    beaconIndicator:SetColorTexture(needsBeacon and 1 or 0, needsBeacon and 0 or 1, 0, 1)
    beaconIndicator:SetAlpha(1)  -- 始终可见
end

-- 改进后的治疗量计算
local function GetHealAmount(spellName)
    local base = select(7, GetSpellInfo(spellName == "圣光术" and 635 or 19750))
    local coeff = 1.5
    if spellName == "圣光闪现" then base, coeff = 220, 0.8 end

    local sp = GetSpellBonusHealing()
    local critChance = GetCritChance() / 100
    return (base + sp * coeff) * (1 + critChance * 0.5) -- 假设暴击治疗150%
end

-- 主逻辑
local function UpdateIcons()
    healIcon:Hide()

    if not UnitExists("target") or UnitIsDeadOrGhost("target") or not UnitIsConnected("target") then
        return
    end

    if not UnitExists("target") or UnitIsDeadOrGhost("target") then return end

    local currentHealth = UnitHealth("target")
    local maxHealth = UnitHealthMax("target")
    local missingHealth = maxHealth - currentHealth

    -- 新增：治疗缺口必须大于0
    if missingHealth <= 0 then return end

    local hlHeal = GetHealAmount("圣光术")
    local folHeal = GetHealAmount("圣光闪现")

    -- 修正判断逻辑
    if missingHealth > folHeal then  -- 当缺口超过闪现治疗量
        healIcon:SetTexture(holyLightIcon)
        healIcon:Show()
    elseif missingHealth > 0 then     -- 当缺口小于闪现治疗量但大于0
        healIcon:SetTexture(flashOfLightIcon)
        healIcon:Show()
    end
end

-- 表格包含检查函数
local function tContains(tbl, item)
    for _, v in ipairs(tbl) do
        if v == item then
            return true
        end
    end
    return false
end


-- 改进的祝福检测 --
local function CheckBlessings()
    if not UnitExists("target") or not UnitIsPlayer("target") then return {} end

    local playerBlessing = false  -- 玩家是否已施加任何祝福
    local appliedBlessings = {}  -- 记录已存在的祝福类型

    -- 第一步：检测所有已应用的祝福
    for i=1, 40 do
        local name, _, _, _, _, _, source, _, _, spellId = UnitAura("target", i, "HELPFUL")
        if not name then break end

        -- 检查是否属于任意祝福类型
        for blessType, info in pairs(BLESSING_INFO) do
            if tContains(info.spellIDs, spellId) then
                appliedBlessings[blessType] = true
                if source == "player" then  -- 直接判断来源单位
                    playerBlessing = true
                end
            end
        end
    end

    -- 第二步：根据玩家施加状态决定显示逻辑
    if playerBlessing then
        return {}  -- 玩家已施加过任意祝福，不显示任何图标
    else
        -- 仅显示缺失的祝福
        local missing = {}
        for blessType, _ in pairs(BLESSING_INFO) do
            if not appliedBlessings[blessType] then
                table.insert(missing, blessType)
            end
        end
        return missing
    end
end

-- 更新界面逻辑 --
local function UpdateUI()
    -- 隐藏所有祝福图标
    for _, icon in pairs(blessingIcons) do
        icon:Hide()
    end

    -- 检测缺失祝福（原逻辑不变）
    local missing = CheckBlessings()
    if #missing > 0 then
        -- 仅更新祝福图标位置
        for i, blessName in ipairs(missing) do
            local icon = blessingIcons[blessName]
            icon:ClearAllPoints()
            icon:SetPoint("LEFT", dragFrame, "LEFT", (i-1)*35, 0)
            icon:Show()
        end
        dragFrame:SetWidth(#missing * 35)
    else
        dragFrame:SetWidth(1)
    end
end

-- 事件处理
frame:SetScript("OnEvent", function(self, event, ...)
    if event == "PLAYER_TARGET_CHANGED" then
        -- 目标变化时同时更新治疗和祝福状态
        UpdateIcons()
        UpdateUI()
    elseif event == "UNIT_HEALTH" or event == "UNIT_MAXHEALTH" then
        local unit = ...
        if unit == "target" then
            UpdateIcons()  -- 仅更新治疗指示
        end
    elseif event == "SPELL_POWER_CHANGED" then
        UpdateIcons()  -- 法强变化影响治疗量
    elseif event == "UNIT_AURA" then
        local unit = ...;
        if unit == "target" then
            UpdateUI()  -- 仅更新祝福状态
        end
    end
    -- 应合并为：
    if event == "PLAYER_FOCUS_CHANGED" or (event == "UNIT_AURA" and select(1, ...) == "focus") then
        UpdateBeaconIndicator()
    end
end)

-- 加入暴击率计算
local function GetCritChance()
    return GetCritChance() -- 从API获取治疗暴击率
end

-- 替换为开关状态控制函数
local function ToggleAutoBeacon()
    SWITCH_STATE = not SWITCH_STATE
    switchIndicator:SetColorTexture(SWITCH_STATE and 0 or 1, SWITCH_STATE and 1 or 0, 0, 0.8)
end




